package cn.zhihong.controller;

import cn.zhihong.common.R;
import cn.zhihong.dto.UserDto;
import cn.zhihong.pojo.User;
import cn.zhihong.service.UserService;
import cn.zhihong.utils.SMSUtils;
import cn.zhihong.utils.ValidateCodeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @ClassName UserController
 * @Author 庄志宏
 * @Date 2022/4/26 12:25
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * @author 庄志宏
     * @date: 2022/4/26 12:27
     * 发送手机短信验证码
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotBlank(phone)){
            // 生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("短信验证码为：{}",code);
            //调用阿里云提供的短信服务API完成发送短信
//            SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);
            //需要将生成的验证码保存到session中
            session.setAttribute(phone,code);
            return R.success("短信发送成功");
        }
        return R.error("短信发送失败");
    }
    /**
     * @author 庄志宏
     * @date: 2022/4/26 16:02
     * 移动端用户登录
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody UserDto userDto, HttpSession session){
        log.info("移动端输入的手机号和验证码：{}",userDto);
        //获取手机号码
        String phone = userDto.getPhone();
        //获取验证码
        String code = userDto.getCode().toString();
        //从session中获取保存的验证码
        Object sessionCode = session.getAttribute(phone);
        //进行验证码的比对
        if (sessionCode == null || !sessionCode.equals(code)){
            return R.error("登录失败");
        }
        //如果比对成功，说明登录成功
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getPhone,phone);
        User user = userService.getOne(userLambdaQueryWrapper);
        //判断是否是新用户
        if (user == null){
            user = new User();
            user.setPhone(phone);
            userService.save(user);
        }
        session.setAttribute("user",user.getId());
        return R.success(user);
    }
    /**
     * @author 庄志宏
     * @date: 2022/4/27 12:15
     * 退出登陆
     */
    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){
        log.info("客户端退出登陆");
        session.removeAttribute("user");
        return R.success("退出登陆成功");
    }
}
